--
-- Author: shunguo.chen
-- Date: 2016-06-20 12:47:35
--
-- PayView

local CoinRender = require("app.widget.renders.CoinRender")
local GoldRender = require("app.widget.renders.GoldRender")
local PayPanel = import(".PayPanel")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

ClassRef.VIEW_ROOT_RES = Res.PayScene

function ClassRef:init()
	local root = self._ui.pay

	self._curPage = 0
	self._maxPage = 0

	self._goldCon = CoinRender.create(root:findChild("coin_my/coinmy_node"))
	self._coinCon = CoinRender.create(root:findChild("coin_my/diammy_node"))
	self._titleText = root:findChild("01title/tlt_text")
	self._pageText = root:findChild("page/04Num")

	local function pageViewEvent(sender, eventType)
        if eventType == ccui.PageViewEventType.turning then
            local pageIndex = sender:getCurPageIndex()
            if self._curPage == pageIndex then return end
            self._curPage = pageIndex
            self:switchPage()
        end
    end
	self._pageView = root:findChild("PageView")
	self._pageView:setCustomScrollThreshold(1/3 * self._pageView:getContentSize().width)
    self._pageView:addEventListener(pageViewEvent)
    self._pageSize = self._pageView:getContentSize()

    self._leftBtn = root:findChild("arrow_1")
    self._rightBtn = root:findChild("arrow_2")
    self._leftBtn:addClickEventListener(function()
			self._pageView:scrollToPage(self._curPage - 1)
		end)
    self._rightBtn:addClickEventListener(function()
			self._pageView:scrollToPage(self._curPage + 1)
		end)

	root:findChild("Btn_back/Button_back"):addClickEventListener(function()
			executeFunc(self._onCloseView)
		end)
end

function ClassRef:getPages()
	return self._pageView:getPages()
end

function ClassRef:getAllItems()
	local pages = self:getPages()
	local allItems = {}
	for _,page in ipairs(pages) do
		local items = page:getItems()
		for _,item in ipairs(items) do
			allItems[#allItems + 1] = item
		end
	end
	return allItems
end

function ClassRef:setMaxPage(max)
	if self._maxPage ~= max then
		self._maxPage = max
		local pages = self._pageView:getPages()
		local sub = max - #pages
		if sub > 0 then
			while sub > 0 do
				local page = PayPanel.create()
				self._pageView:addPage(page)
				sub = sub - 1
			end
		elseif sub < 0 then
			local len = #pages
			while len > max do
				self._pageView:removePageAtIndex(len-1)
				len = len - 1
			end
		end

		if self._curPage >= self._maxPage then
			self._curPage = self._maxPage - 1
		end
		self:switchPage()
	end
end

function ClassRef:switchPage()
	display.setBtnTouchEnable(self._leftBtn, self._curPage > 0)
	display.setBtnTouchEnable(self._rightBtn, self._curPage < (self._maxPage - 1))
	self._pageText:setString((self._curPage+1) .. "/" .. self._maxPage)
end

function ClassRef:updateCoin(num)
	self._coinCon:setText(num)
end

function ClassRef:updateGold(num)
	self._goldCon:setText(num)
end

return ClassRef